<template>
  <div class="home-page">
    <div class="right-view" v-loading="loading">
      <div class="right-view-search">
        <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName" class="input-with-select">
          <template #append>
            <el-button class="input-with-button" @click="searchSchool">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="right-view-search" style="margin-top: 10px;">
        <el-tabs v-model="activeIndex" type="card" @tab-click="handleClick">
          <el-tab-pane v-for="(item) in state.areaList" :key="item.id" :label="item.name" :name="item.id"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="right-view-add" v-if="operationStatus === 'true'">
        <el-button type="primary" @click="operationalData('add')">新增</el-button>
        <div style="width: 250px;margin-left: 30px;">
          <span style="font-size: 14px;">分配状态:</span>
          <el-select style="width: 55%;margin-left: 10px" v-model="assigned" @change="changeAssigned" placeholder="请选择分配状态">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="已分配" :value="1"></el-option>
            <el-option label="未分配" :value="2"></el-option>
          </el-select>
        </div>
        <div style="width: 250px;margin-left: 10px;">
          <span style="font-size: 14px;">启用状态:</span>
          <el-select style="width: 55%;margin-left: 10px" v-model="status" @change="changeAssigned" placeholder="请选择启用状态">
            <el-option label="全部" :value="-1"></el-option>
            <el-option label="未启用" :value="0"></el-option>
            <el-option label="已启用" :value="1"></el-option>
          </el-select>
        </div>
        <div style="margin-right: 20px;"><el-button type="warning" @click="uploadGPA(1)">上传系GPA</el-button></div>
        <div style="margin-right: 20px;"><el-button type="warning" @click="uploadGPA(2)">上传指定专业GPA</el-button></div>
        <div style="margin-right: 20px;"><el-button type="warning" @click="uploadGPA(3)">上传专业数据</el-button></div>
        <div style="margin-right: 20px;"><el-button type="warning" @click="uploadGPA(4)">添加硕士/预科专业</el-button></div>
      </div>
      <div class="right-view-table" v-if="state.listData.length > 0">
        <el-table  :max-height='state.posheight' :data="state.listData" border style="width: 100%">
          <el-table-column label="学校logo" show-overflow-tooltip align="center">
            <template #default="scope">
              <el-image v-if="scope.row.logo" style="width: 100px; height: 100px" :src="scope.row.logo"/>
              <img v-else src="@/assets/img/no-img.png" alt="">
           </template>
          </el-table-column>
          <el-table-column label="学校名称" show-overflow-tooltip align="center">
            <template #default="scope">
              <span :style="scope.row.pid == 0 ? 'color: red;' : ''">{{ scope.row.name_zh || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学校英文名称" show-overflow-tooltip align="center">
            <template #default="scope">{{ scope.row.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="代理人"  width="140" show-overflow-tooltip align="center">
            <template #default="scope">{{ scope.row.agent || '-' }}</template>
          </el-table-column>
          <el-table-column v-if="operationStatus === 'true'" label="是否启用" show-overflow-tooltip width="140" align="center">
            <template #default="scope">
              <el-switch :before-change="() => onBeforeChange(scope.row)" v-model="scope.row.status" :active-value="1" :inactive-value="0" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="所在地区" show-overflow-tooltip align="center">
            <template #default="scope">
              <span  v-for="(item) in state.areaList" :key="item.id">
                <span v-if="scope.row.areas_id == item.id">{{ item.name }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="排名" sortable prop="qs" show-overflow-tooltip align="center">
            <template #default="scope">{{ scope.row.qs || '-'}}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="330" show-overflow-tooltip align="center">
            <template #default="scope">
              <el-button @click.prevent="details(scope.row)" type="warning" size="small">学院详情</el-button>
              <el-button @click.prevent="updateRow(scope.row,'update')" type="primary" size="small">学校修改</el-button>
              <el-button @click.prevent="editTemplateConfig(scope.row)" type="success" size="small">模板配置</el-button>
              <el-button v-if="operationStatus === 'true'" type="danger" @click.prevent="deleteSchool(scope.row)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="right-view-page">
          <el-pagination 
            layout="total, prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
            :page-size="10"
            :pageSizes='[10, 20, 30, 40]'
            :current-page="currentPage">
          </el-pagination>
        </div>
      </div>
      <div v-else class="right-view-nodata">
        <img src="../assets/img/no-data.png" alt="">
        <div>暂无数据</div>
      </div>
    </div>
    <el-dialog
      width="40%"
      :title="titleName + '学校数据'"
      :close-on-click-modal="false"
      v-model="schoolVisible">
      <addSchool v-if="schoolVisible" :parmas="{itemInfo:state.itemInfo,type:clickStatus}" @closeAddSchool="closeAddSchool"></addSchool>
    </el-dialog>
    <!-- 模板配置弹窗 -->
    <el-dialog
      width="35%"
      title="模板配置"
      :close-on-click-modal="false"
      v-model="configVisible">
      <templateConfig v-if="configVisible" :parmas="{itemInfo:state.itemInfo}" @closeConfig="closeConfig"></templateConfig>
    </el-dialog>
    <el-dialog
    width="20%"
    title="请选择Excel文件导入"
    :close-on-click-modal="false"
    v-model="state.showGpaVisible">
    <div v-if="state.showGpaVisible" style="margin-top: 15px;">
      <div class="view-main-table-upload">
        <input type="file" @change="handleFileChange" accept=".xlsx, .xls">
      </div>
      <el-button type="primary" @click="uploadFile">提交</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref,reactive,computed,onMounted, watch } from 'vue';
import addSchool from "./schoolComponents/add-school"
import templateConfig from './schoolComponents/template-config.vue'
import { ElMessage ,ElMessageBox} from 'element-plus';
import { serverUrl } from '@/utils/const'
import { useStore } from 'vuex';
import API from "@/utils/api";
import axios from 'axios';
import { useRouter } from "vue-router";
const store = useStore();
const router = useRouter()
const menuList = computed(() => store.state.menuList);
let schoolName = ref('')
let status = ref(-1)
let total = ref(0)
let loading = ref(false)
let currentPage = ref(1)
let activeIndex = ref(1)
let schoolVisible = ref(false)
let clickStatus = ref('')
let titleName = ref('新增')
let configVisible = ref(false)
let assigned = ref(0)
let operationStatus = ref(localStorage.getItem('operationStatus'))
let state = reactive({
  listData: [],
  areaList:[],
  itemInfo:{},
  h: document.body.clientHeight,
  posheight: 100,
  timer: false,
  showGpaVisible: false,
  selectedFile1:'',
  selectedFile2:'',
  selectedFile3:'',
  selectedFile4:'',
  GPAvalue:'',
});
watch(() => state.h, (newValue, oldValue) => {
  if(!state.timer) {
    state.posheight = newValue - 220
    state.timer = true
    setTimeout(function (){
      state.timer = false
    },400)
  }
})
const uploadGPA = ((val) => {
  state.GPAvalue = val
  state.showGpaVisible = !state.showGpaVisible
})
const handleFileChange = (event) => {
  if(state.GPAvalue == 1) {
    state.selectedFile1 = event.target.files[0];
  }else if(state.GPAvalue == 2){
    state.selectedFile2 = event.target.files[0];
  }else if(state.GPAvalue == 3){
    state.selectedFile3 = event.target.files[0];
  }else if(state.GPAvalue == 4){
    state.selectedFile4 = event.target.files[0];
  }
};
async function uploadFile() {
  if(state.GPAvalue == 1 && !state.selectedFile1) {
    return ElMessage.warning('请选择要上传的excel文件')
  }
  if(state.GPAvalue == 2 && !state.selectedFile2) {
    return ElMessage.warning('请选择要上传的excel文件')
  }
  if(state.GPAvalue == 3 && !state.selectedFile3) {
    return ElMessage.warning('请选择要上传的excel文件')
  }
  if(state.GPAvalue == 4 && !state.selectedFile4) {
    return ElMessage.warning('请选择要上传的excel文件')
  }
  const formData = new FormData();
  try {
    if(state.GPAvalue == 1) {
      formData.append('file', state.selectedFile1);
      const response = await axios.post(serverUrl+'/mat/updateGpaOfDepartment?YJxnSrqw=aabb66864fa795f0ccc1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token-admin': localStorage.getItem('token'),
        }
      });
      if(response.data.code === 0) {
        state.selectedFile1 = ''
        state.showGpaVisible = false
        getschoolInfoList()
        ElMessage.success('上传成功')
      }
      if(response.data.code === 400) {
        ElMessage.warning(response.data.msg)
      }
      if(response.data.code === 401) {
        ElMessage.warning('未登录')
        router.push({path: '/'})
        localStorage.removeItem('token')
        localStorage.removeItem('operationStatus')
      }
    }else if(state.GPAvalue == 2){
      formData.append('file', state.selectedFile2);
      const response = await axios.post(serverUrl+'/mat/updateDegreesGpaOfDepartment?YJxnSrqw=aabb66864fa795f0ccc1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token-admin': localStorage.getItem('token'),
        }
      });
      if(response.data.code === 0) {
        state.selectedFile2 = ''
        state.showGpaVisible = false
        getschoolInfoList()
        ElMessage.success('上传成功')
      }
      if(response.data.code === 400) {
        ElMessage.warning(response.data.msg)
      }
      if(response.data.code === 401) {
        ElMessage.warning('未登录')
        router.push({path: '/'})
        localStorage.removeItem('token')
        localStorage.removeItem('operationStatus')
      }
    }else if(state.GPAvalue == 3){
      formData.append('file', state.selectedFile3);
      const response = await axios.post(serverUrl+'/mat/updateDegreeFields?YJxnSrqw=aabb66864fa795f0ccc1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token-admin': localStorage.getItem('token'),
        }
      });
      if(response.data.code === 0) {
        state.selectedFile3 = ''
        state.showGpaVisible = false
        getschoolInfoList()
        ElMessage.success('上传成功')
      }
      if(response.data.code === 400) {
        ElMessage.warning(response.data.msg)
      }
      if(response.data.code === 401) {
        ElMessage.warning('未登录')
        router.push({path: '/'})
        localStorage.removeItem('token')
        localStorage.removeItem('operationStatus')
      }
    }else if(state.GPAvalue == 4){
      formData.append('file', state.selectedFile4);
      const response = await axios.post(serverUrl+'/mat/addPostgraduateDegrees?YJxnSrqw=aabb66864fa795f0ccc1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token-admin': localStorage.getItem('token'),
        }
      });
      if(response.data.code === 0) {
        state.selectedFile4 = ''
        state.showGpaVisible = false
        getschoolInfoList()
        ElMessage.success('上传成功')
      }
      if(response.data.code === 400) {
        ElMessage.warning(response.data.msg)
      }
      if(response.data.code === 401) {
        ElMessage.warning('未登录')
        router.push({path: '/'})
        localStorage.removeItem('token')
        localStorage.removeItem('operationStatus')
      }
    }
  } catch (error) {}
}
// 模板配置
function editTemplateConfig (val) {
  configVisible.value = true
  state.itemInfo = val
}
function closeConfig (val) {
  configVisible.value = false
}
function handleCurrentChange (val) {
  currentPage.value = val
  getschoolInfoList()
}
function details(item) {
  const infos = {
    currentPage:currentPage.value,
    schoolName:schoolName.value,
    status:status.value,
    assigned:assigned.value,
    areas_id:activeIndex.value,
  }
  localStorage.setItem('searchInfos',JSON.stringify(infos))
  router.push({path: '/faculty', query: {
    id:item.id,   //学校ID
    areas_id:item.areas_id,
    logo:item.logo,
    name:item.name,
    name_zh:item.name_zh,
    qs:item.qs,
  }})
}
function operationalData (type) {
  schoolVisible.value = true
  clickStatus.value = type
  state.itemInfo.areas_id = activeIndex.value
  titleName.value = '新增'
}
function updateRow (item,type) {
  schoolVisible.value = true
  state.itemInfo = item
  clickStatus.value = type
  titleName.value = '编辑'
}
function closeAddSchool (type) {
  schoolVisible.value = false
  if(type === 1) {
    getschoolInfoList()
  }
}
function searchSchool () {
  getschoolInfoList()
}
function handleClick (tab, event) {
  currentPage.value = 1
  activeIndex.value = tab.props.name
  getschoolInfoList()
}
// 获取地区数据
function getAreaList () {
  loading.value = true
  API.schoolList.getAreaList({}, (res) => {
    loading.value = false
    if(res.code == 0) {
      state.areaList = res.data
    }
  })
}
function changeAssigned () {
  currentPage.value = 1
  getschoolInfoList()
}
// 获取学校数据
function getschoolInfoList () {
  loading.value = true
  API.schoolList.schoolInfoList({
    status:status.value,
    assigned:assigned.value,
    areas_id:activeIndex.value,
    name:schoolName.value,
    page:currentPage.value,
    limit:10,
  }, (res) => {
    loading.value = false
    if(res.code == 0) {
      state.listData = res.data.details
      total.value = res.data.total
    }
  })
}
function posTableHeight () {
  let h = document.body.clientHeight,
  new_h = h - 220;
  state.posheight = new_h;
}
function deleteSchool (row) {
  return new Promise((resolve) => {
    ElMessageBox.confirm('你确定要删除此条学校数据吗', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    }).then(() => {
      API.schoolList.delSchoolData({id:row.id}, (res) => {
        if(res.code == 0) {
          getschoolInfoList()
        }
      })
      return resolve()
    }).catch(() => {
      // ElMessage({type: 'info',message: '已取消操作',});
    });
  })
}
function onBeforeChange (row) {
  return new Promise((resolve) => {
    ElMessageBox.confirm(`${row.toggle_msg}`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    }).then(() => {
      API.schoolList.operationCollege({id:row.id}, (res) => {
        if(res.code == 0) {
          getschoolInfoList()
        }
      })
      return resolve()
    }).catch(() => {
      // ElMessage({type: 'info',message: '已取消操作',});
    });
  })
}
onMounted(() => {
  const infos = JSON.parse(localStorage.getItem('searchInfos'))
  if(infos) {
    currentPage.value = infos.currentPage
    schoolName.value = infos.schoolName
    status.value = infos.status
    assigned.value = infos.assigned
    activeIndex.value = infos.areas_id
  }
  console.log(infos);
  getAreaList()
  getschoolInfoList()
  posTableHeight()
  window.onresize = () => {
    return (() => {
      let a = document.body.clientHeight
      state.h = a
    })()
  }
})
</script>

<style lang="scss" scoped>
.view-main-table-upload {
  margin-bottom: 20px;
  text-align: start;
}
.home-page {
  padding: 20px;
  .right-view {
    // background: #fcfbfb;
    .right-view-search {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      .input-with-button {
        color: #fff;
        background: #409eff;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
      .el-tabs {
        --el-tabs-header-height: 30px;
      }
      .el-input-group {
        width: 370px;
      }
    }
    .right-view-nodata {
      margin-top: 170px;
    }
    .right-view-add {
      text-align: start;
      display: flex;
      align-items: center;
    }
    .right-view-table {
      margin-top: 20px;
      max-height: calc(100% - 200px);
    }
    .right-view-page {
      display: flex;
      justify-content: end;
      margin-top: 15px;
    }
  }
  /*选中时底部边颜色*/
  ::v-deep .el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
    border: 1px solid #3275f9;
  }
  ::v-deep .el-tabs--card>.el-tabs__header .el-tabs__item:first-child {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
  }
  ::v-deep .el-tabs--card>.el-tabs__header .el-tabs__item:last-child {
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  ::v-deep .el-dialog__header {
    text-align: left;
    font-size: 15px;
    font-weight: 600;
  }
}
</style>